//
//  OrderConfirmVC.m
//  ImGuider
//
//  Created by 王鹏宇 on 2017/12/13.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "OrderConfirmVC.h"
#import "TicketInforCell.h"
#import "TravelPersonsCell.h"
#import "contactsInforCell.h"
#import "PaymentTypeCell.h"
#import "CalendarSelectedVC.h"
#import "TicketMemberInfoModel.h"
#import "OrderPayManager.h"
#import "TicketPayMentResultVC.h"
#import "IGDatePickerView.h"
#import "PlayerItem.h"
#import "XHPKit.h"
@interface OrderConfirmVC ()<UITableViewDataSource,UITableViewDelegate,PayTypeDelegate,IGDatePickerViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *priceLabel;

@property (weak, nonatomic) IBOutlet UIButton *paymentBtn;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomSpace;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;

@property (nonatomic, assign)BOOL isHide;
@property (nonatomic, strong)IGDatePickerView * datePicker;

@property (nonatomic, strong) NSArray * mustLimitArray;//限制必填项

//购买所需参数

@property (nonatomic)PayType paytype;//支付类型

//@property (nonatomic, strong) TicketMemberInfoModel * memberInfoModel;//所填的信息

//detial【】 [self.ticketOrderModel orderRequestInfoArray]

@end

@implementation OrderConfirmVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setup];
    
    [self setupData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[PlayerItem playItemShareManager] show];
    self.isHide = NO;
    if(self.ticketOrderModel.orderid){
        [self.tableView reloadData];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (self.isHide) {
        [[PlayerItem playItemShareManager] hide];
    }
}
- (UploadTicketOrderModel *)ticketOrderModel {
    
    if (!_ticketOrderModel) {
        
        _ticketOrderModel = [[UploadTicketOrderModel alloc] init];
    }
    
    return _ticketOrderModel;
}

- (void)setup {
    
    self.title = MYLocalizedString(@"PAYORDER_PAY", nil);
    [self.tableView registerNib:[UINib nibWithNibName:@"TicketInforCell" bundle:nil] forCellReuseIdentifier:@"TicketInforCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TravelPersonsCell" bundle:nil] forCellReuseIdentifier:@"TravelPersonsCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"contactsInforCell" bundle:nil] forCellReuseIdentifier:@"contactsInforCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"PaymentTypeCell" bundle:nil] forCellReuseIdentifier:@"PaymentTypeCell"];
    
    [self.tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"headerView"];
    
    [self.paymentBtn setTitle:MYLocalizedString(@"PAYORDER_PAY", nil) forState:UIControlStateNormal];
    self.mustLimitArray = @[@"firstname",@"lastname",@"passportno",@"passportcountry",@"birthday",@"countrycode",@"email"];
    
    [self setNavThemeGradient];
    [self createBackBtn];
}

-(void)createBackBtn{
    
    UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    self.navigationItem.leftBarButtonItem = barItem;
    
}

-(void)back {
    
    if(!self.type){
    [IGAlertView alertWithTitle:[NSString stringWithFormat:@"%@?",MYLocalizedString(@"TICKET_ORDER_CABCEL", nil)] message:MYLocalizedString(@"TICKET_ORDER_CABCEL_TIP", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"PUBLIC_CONFIRM", nil) commit:^{
        
        [self.navigationController popViewControllerAnimated:YES];
        
    } cancel:nil];
    }else{
         [self.navigationController popViewControllerAnimated:YES];
    }
}

- (IGDatePickerView *)datePicker {
    if (!_datePicker) {
        
        _datePicker = [[IGDatePickerView alloc] init];
        _datePicker.delegate = self;
    }
    
    return _datePicker;
    
}
- (void)setupData {
    
    if (self.ticketOrderModel.ordernumber.length > 0) {
        self.priceLabel.text = self.ticketOrderModel.realpay;
    }else{
        self.priceLabel.text = self.ticketOrderModel.amount;
    }
    
     [self.tableView reloadData];
}
- (IBAction)paymentBtnClicked:(UIButton *)sender {
    
    self.isHide = YES;
    
    switch (self.paytype) {
        case PayTypeWX: {
            
            if (![XHPKit isWxAppInstalled]) {
                
                [IGUtil showToast:@"未安装微信"];
                
                return;
            }
            
            break;
        }
        case PayTypeAlipay: {
            
            if (![XHPKit isAliAppInstalled]) {
                
                [IGUtil showToast:@"未安装支付宝"];
                
                return;
            }
            
            break;
        }
        default:
            break;
    }
    
    if (self.ticketOrderModel.orderid.length > 0) {
        
        [self repay];
    }else{
        [self goPay];
    }
    
}
- (void)repay {
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    @weakify(self);
    [[OrderPayManager sharedManager] reticketWithOrderID:self.ticketOrderModel.orderid payType:self.paytype vc:self andBlock:^(NSString *result, NSError *error) {
        
        @strongify(self);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        
        TicketPayMentResultVC * payResultVC = [[TicketPayMentResultVC alloc] init];
        payResultVC.ticketOrderModel = self.ticketOrderModel;
        self.isHide = NO;
        if (!error) {
            
            payResultVC.payState = 1;//1 成功  2 失败
    
        }else{
            payResultVC.payState = 2;//1 成功  2 失败
        }
        
        if (self.ticketOrderModel.ordernumber) {
            payResultVC.isRePay = YES;
        }else{
            payResultVC.isRePay = NO;
        }
        
        [self.navigationController pushViewController:payResultVC animated:YES];
        
        if (error.code == PAY_FILEDCOED_SERVERERROR) {
            
            [IGAlertView alertWithTitle:MYLocalizedString(@"PAYORDER_FAILED_TITLE", nil) message:MYLocalizedString(@"PAYORDER_FAILED_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"MYORDER_CONTACTSTAFF", nil) commit:^{
                UIViewController *contactService = [IGUtil loadViewController:@"ContactService" storyboard:@"Account"];
                [self.navigationController pushViewController:contactService animated:YES];
            } cancel:nil];
            
        } else {
            
            [IGUtil showToast:[IGUtil tipFromError:error]];
        }
        return;
    }];
}

- (void)goPay {
    
    if ([self checkContent]) {
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        @weakify(self);
        
        [[OrderPayManager sharedManager] ticketModel:self.ticketOrderModel payType:self.paytype vc:self andBlock:^(NSString *result, NSError *error) {
            
            @strongify(self);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
    
            TicketPayMentResultVC * payResultVC = [[TicketPayMentResultVC alloc] init];
            self.isHide = NO;
            payResultVC.ticketOrderModel = self.ticketOrderModel;
            if (!error) {
                
                payResultVC.payState = 1;//1 成功  2 失败
                
            }else{
                
                payResultVC.payState = 2;//1 成功  2 失败
            }
            [self.navigationController pushViewController:payResultVC animated:YES];
            
            if (error.code == PAY_FILEDCOED_SERVERERROR) {
                
                [IGAlertView alertWithTitle:MYLocalizedString(@"PAYORDER_FAILED_TITLE", nil) message:MYLocalizedString(@"PAYORDER_FAILED_CONTENT", nil) cancelButtonTitle:MYLocalizedString(@"PUBLIC_CANCEL", nil) commitBtn:MYLocalizedString(@"MYORDER_CONTACTSTAFF", nil) commit:^{
                    UIViewController *contactService = [IGUtil loadViewController:@"ContactService" storyboard:@"Account"];
                    [self.navigationController pushViewController:contactService animated:YES];
                } cancel:nil];
                
            } else {
                
                [IGUtil showToast:[IGUtil tipFromError:error]];
            }
            return;
            
        }];
        
    }else {
        [IGAlertView alertWithTitle:MYLocalizedString(@"TICKET_SELECT_RESERVATION_TIP", nil) message:MYLocalizedString(@"TICKET_SELECT_RESERVATION_INFO", nil) cancelButtonTitle:MYLocalizedString(@"TICKET_SELECT_RESERVATION_GOON", nil) commitBtn:nil commit:nil cancel:^{
            
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:(UITableViewScrollPositionTop) animated:YES];
        }];
    }
}

- (void)selectBirthdayDate{
    
    self.sl_popupController.layoutType = PopupLayoutTypeBottom;
    [self.sl_popupController presentContentView:self.datePicker];
    
    self.datePicker.selectedDate = self.ticketOrderModel.contact.birthdayDate;
}

#pragma mark -- IGDatePickerViewDelegate

- (void)cancelSelet{
    
    [self.sl_popupController dismiss];
}

- (void)confirmTheDate:(NSDate *)date {
    
    self.ticketOrderModel.contact.birthdayDate = date;
    self.ticketOrderModel.contact.birthday = [date stringWithFormat:@"yyyy-MM-dd"];
    [self.tableView reloadData];
    [self.sl_popupController dismiss];
}
#pragma mark -- PayTypeDelegate

- (void)seletedPayType:(PayType)payType {
    
    self.paytype = payType;
}

#pragma mark   -- UITableViewDataSource,UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:
        {
            TicketInforCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TicketInforCell"];
            
            cell.ticketNameLabel.text = self.ticketOrderModel.subject;
            if (self.ticketOrderModel.orderdate.length > 0) {
                
                NSString *str = MYLocalizedString(@"TICKET_ORDER_DATE", nil);
                cell.dateLabel.text = [NSString stringWithFormat:@"%@%@",str,self.ticketOrderModel.orderdate];
            }
            if (self.ticketOrderModel.orderInfo.length > 0) {
                 cell.ticketDetailLabel.text = self.ticketOrderModel.orderInfo;
            }
            
            return cell;
        }
            break;
        case 1:
        {
            TravelPersonsCell * cell = [tableView dequeueReusableCellWithIdentifier:@"TravelPersonsCell"];
            
            cell.dataSource = self.ticketOrderModel.Allpersons;
            return cell;
        }
            break;
        case 2:
        {
            contactsInforCell * cell = [tableView dequeueReusableCellWithIdentifier:@"contactsInforCell"];
            cell.superVC = self;
            cell.memberModel = self.ticketOrderModel.contact;
            
            if (self.ticketOrderModel.orderid.length > 0) {
                
                [cell configDataWith:self.ticketOrderModel.contact];
            }
            return cell;
            
        }
            break;
        case 3:
        {
            PaymentTypeCell * cell = [tableView dequeueReusableCellWithIdentifier:@"PaymentTypeCell"];
            
            cell.delegate = self;
            return cell;
        }
            break;
            
        default:
            
             return nil;
            break;
    }
    
   
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UITableViewHeaderFooterView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    
    headerView.backgroundColor = kBGColor;
    
    return headerView;
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:
        {
            return 116;
        }
            break;
        case 1:
        {
            if (self.ticketOrderModel.Allpersons.count > 0) {
                
                return (self.ticketOrderModel.Allpersons.count + 1) * 50;
            }
            return 0;
        }
            break;
        case 2:
        {
            return 194;
            
        }
            break;
        case 3:
        {
//            if([[AppManager sharedManager].currencyCode isEqualToString:@"USD"]){
//                return 100;
//            }else{
//
//            }
            
            return 150;
            
        }
            break;
            
        default:
            
            return 0;
            break;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (self.ticketOrderModel.Allpersons.count == 0 && section == 1) {
        
        return 0.000001;
    }
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.00001;
}



- (BOOL)checkContent {
    
    BOOL flag = YES;
    
    if (![self stringIsHaveContentWith:self.ticketOrderModel.contact.email]) {
        
        flag = NO;
    }
    
    if (![self stringIsHaveContentWith:self.ticketOrderModel.contact.countrycode] || ![self stringIsHaveContentWith:self.ticketOrderModel.contact.phoneNumber]) {
        flag = NO;
    }
    
    if (![self stringIsHaveContentWith:self.ticketOrderModel.contact.realname]) {
        flag = NO;
    }
    
//    for (NSString * str in self.mustLimitArray) {
//        
//        if ([str isEqualToString:@"email"]) {
//            
//            
//        }else if([str isEqualToString:@"firstname"]){
//            if (![self stringIsHaveContentWith:self.ticketOrderModel.contact.firstname]) {
//                
//                flag = NO;
//            }
//            
//        }else if([str isEqualToString:@"lastname"]){
//            
//            if (![self stringIsHaveContentWith:self.ticketOrderModel.contact.lastname]) {
//                
//                flag = NO;
//            }
//            
//        }else if([str isEqualToString:@"passportno"]){
//            
//            if (![self stringIsHaveContentWith:self.ticketOrderModel.contact.passportno]) {
//                
//                flag = NO;
//            }
//        }else if([str isEqualToString:@"passportcountry"]){
//            
//            if (![self stringIsHaveContentWith:self.ticketOrderModel.contact.passportcountry]) {
//                
//                flag = NO;
//            }
//        }else if([str isEqualToString:@"birthday"]){
//            
//            if (![self stringIsHaveContentWith:self.ticketOrderModel.contact.birthday]) {
//                
//                flag = NO;
//            }
//        }else if([str isEqualToString:@"countrycode"]){
//            
//           
//        }
//        
//    }
    
    return flag;
}

- (BOOL)stringIsHaveContentWith:(NSString *)str {
    
    NSString * content =  [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    return content.length > 0? YES:NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
